﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.UI.WebControls;
using System.Data;
using BYFW.WebBase;
using BYFW.BOL;
using System.IO;
using System.Web.UI.DataVisualization.Charting;
using System.Collections;
using System.Drawing;
using BYFW.SFL;
using LDSP.BRL;
using System.Web.UI;

namespace LDSP.Helper
{
    public class UIHelper
    {
        /// <summary>
        /// 同步两个结构相同的grid的head显示状态：用于表头固定场合
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="compare"></param>
        public static void SyncGridHeadColumn(GridView origin, GridView compare)
        {
            for (int i = 0; i < origin.Columns.Count; i++)
            {
                compare.Columns[i].HeaderText = origin.Columns[i].HeaderText;
                compare.Columns[i].Visible = origin.Columns[i].Visible;
            }
        }
        /// <summary>
        /// 绑定一个表头加一个空行，用于表头固定场合，空行用于控制列宽，可以在显示时被遮盖掉
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="dataSource"></param>
        public static void BindEmptyHeader(GridView grid, DataTable dataSource)
        {
            DataTable headDT = dataSource.Clone();

            DataRow row = headDT.NewRow();
            if (headDT.Columns.Contains("id"))
            {
                row["id"] = 9999;
            }

            headDT.Rows.Add(row);

            grid.DataSource = headDT;
            grid.DataBind();
        }
        /// <summary>
        /// 跨页显示Grid中的选中项，跨页的选中项的ID保存在Hidden控件中
        /// </summary>
        /// <param name="row"></param>
        /// <param name="ettID"></param>
        /// <param name="hidCtrl"></param>
        /// <param name="attName"></param>
        /// <param name="chbName"></param>
        public static void ShowMultiPageChecked(GridViewRow row, int ettID, HiddenField hidCtrl, string attName = "docid", string chbName = "chb")
        {
            CheckBox chb = (CheckBox)row.FindControl(chbName);
            if (chb != null)
            {
                chb.Attributes[attName] = ettID.ToString();
                if (hidCtrl.Value.IndexOf("," + ettID + ",") > -1)
                {
                    chb.Checked = true;
                }
            }
        }
        /// <summary>
        /// 使用PageInfo来绑定页面上的Grid
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="pageInfo"></param>
        /// <param name="dataSource"></param>
        public static void BindGridWithPageInfo(GridView grid, PageInfo pageInfo, DataTable dataSource)
        {
            grid.PageSize = pageInfo.PageSize;
            grid.PageIndex = pageInfo.PageIndex;
            grid.DataSource = dataSource;
            grid.DataBind();
        }
        /// <summary>
        /// 从GridView中绑定的数据行获取数据实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="row"></param>
        /// <returns></returns>
        public static T GetEntityFromGridViewRow<T>(GridViewRow row) where T : BaseEntity, new()
        {
            T res = new T();
            res.GetProperties(((DataRowView)row.DataItem).Row);
            return res;
        }
        /// <summary>
        /// 使Grid的Cell里能正常的显示换行
        /// </summary>
        /// <param name="row"></param>
        /// <param name="index"></param>
        public static void EnableShowEnter(GridViewRow row, params int[] index)
        {
            for (int i = 0; i < index.Length; i++)
            {
                row.Cells[index[i]].Text = row.Cells[index[i]].Text.Replace("\r\n", "<br/>");
            }
        }

        /// <summary>
        /// 使Grid的Cell前后各加一空行
        /// </summary>
        /// <param name="row"></param>
        /// <param name="index"></param>
        public static void AppendEmptyLine(GridViewRow row, params int[] index)
        {
            for (int i = 0; i < index.Length; i++)
            {
                row.Cells[index[i]].Text = "</br>" + row.Cells[index[i]].Text + "</br></br>";
            }
        }

        /// <summary>
        /// 获取全文搜索对应记录的ID列表
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="searchText"></param>
        /// <returns></returns>
        public static List<int> GetPDFFilterIDs(string tableName, string searchText)
        {
            string sql = string.Format("select id from {0} where contains(pdfcontent,'{1}')", tableName, searchText);
            DataTable dt = new BaseEntity().DB.Select(sql).Tables[0];
            List<int> res = new List<int>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int tmp = BYFW.SFL.CommonOP.GetInt(dt.Rows[i][0].ToString(), true);
                res.Add(tmp);
            }
            return res;
        }
        /// <summary>
        /// 获取法规标准全文搜索对应记录的ID列表
        /// </summary>
        /// <param name="searchText"></param>
        /// <returns></returns>
        public static List<int> GetPDFFilterIDsForCodification(string searchText)
        {
            return GetPDFFilterIDs("t_codification", searchText);
        }
        /// <summary>
        /// 获取案例全文搜索对应记录的ID列表
        /// </summary>
        /// <param name="searchText"></param>
        /// <returns></returns>
        public static List<int> GetPDFFilterIDsForAccidentCase(string searchText)
        {
            return GetPDFFilterIDs("t_accidentCase", searchText);
        }
        /// <summary>
        /// 获取新闻全文搜索对应记录的ID列表
        /// </summary>
        /// <param name="searchText"></param>
        /// <returns></returns>
        public static List<int> GetPDFFilterIDsForNews(string searchText)
        {
            return GetPDFFilterIDs("t_news", searchText);
        }
        /// <summary>
        /// 设置通用的图形报表属性
        /// </summary>
        /// <param name="chart"></param>
        /// <param name="title"></param>
        /// <param name="chartType"></param>
        /// <param name="hasLegend"></param>
        /// <param name="xInterval"></param>
        /// <param name="yInterval"></param>
        public static void SetCommonChart(Chart chart, string title, SeriesChartType chartType = SeriesChartType.Pie, bool hasLegend = true, int xInterval = 1, int yInterval = 1)
        {
            chart.Titles.Add(title);
            chart.Titles[0].Font = new Font("Times New Roman", 14, FontStyle.Regular);
            chart.Titles[0].ForeColor = Color.MidnightBlue;

            chart.BackColor = Color.Lavender;
            chart.BackSecondaryColor = Color.Lavender;
            chart.BackGradientStyle = GradientStyle.LeftRight;
            chart.BackImageTransparentColor = Color.White;
            chart.Palette = ChartColorPalette.BrightPastel;

            chart.ChartAreas[0].BackColor = Color.Transparent;
            chart.ChartAreas[0].BorderColor = Color.DimGray;
            chart.ChartAreas[0].BorderDashStyle = ChartDashStyle.Solid;
            chart.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.LightGray;
            chart.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.LightGray;
            chart.ChartAreas[0].AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Solid;
            chart.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Solid;

            if (chartType == SeriesChartType.Pie)
            {
                chart.Series[0].ChartType = chartType;
                chart.Series[0].IsValueShownAsLabel = true;
                chart.ChartAreas[0].Area3DStyle.Enable3D = true;
                //chart.Series[0]["PointWidth"] = "0.5";// Show data points labels  
                //chart.Series[0]["BarLabelStyle"] = "Center";// Show chart as 3D 
                //chart.Series[0]["DrawingStyle"] = "Cylinder";
            }
            else if (chartType == SeriesChartType.StackedBar)
            {
                for (int i = 0; i < chart.Series.Count; i++)
                {
                    chart.Series[i].ChartType = chartType;
                    chart.Series[i].IsValueShownAsLabel = true;
                }
            }
            else if (chartType == SeriesChartType.Bar)
            {
                chart.Series[0].ChartType = chartType;
                chart.Series[0].Color = Color.CornflowerBlue;
                chart.Series[0].BackSecondaryColor = Color.SkyBlue;
                chart.Series[0].BackGradientStyle = GradientStyle.VerticalCenter;
                chart.Series[0].BorderColor = Color.Gray;
                chart.Series[0].BorderWidth = 1;
                chart.Series[0].BorderDashStyle = ChartDashStyle.Solid;
                chart.Series[0].ShadowOffset = 2;
            }
            if (hasLegend)
            {
                chart.Legends.Add("");
                chart.Legends[0].Enabled = true;
                chart.Legends[0].LegendStyle = LegendStyle.Row;
                chart.Legends[0].Docking = Docking.Bottom;
                chart.Legends[0].BackColor = Color.FromName("Transparent");
            }

            chart.ChartAreas[0].AxisX.Interval = xInterval;
            chart.ChartAreas[0].AxisY.Interval = yInterval;
        }
        /// <summary>
        /// 合并字符串中的连续空格为一个空格
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string CombindBlank(string input)
        {
            string pat = @"\s+";
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pat);
            return regex.Replace(input, " ");
        }
        /// <summary>
        /// 设置默认的输入条件提示信息，, 并设置TextBox的字体颜色
        /// </summary>
        /// <param name="txt"></param>
        /// <param name="defaultValue"></param>
        public static void SetDefaultFilterCondition(TextBox txt, string defaultValue)
        {
            SetDefaultFilterCondition(txt, defaultValue, true);
        }

        /// <summary>
        /// 设置默认的输入条件提示信息, 并设置TextBox的字体颜色.
        /// </summary>
        /// <param name="txt"></param>
        /// <param name="defaultValue"></param>
        /// <param name="needSetDefaultValue"></param>
        public static void SetDefaultFilterCondition(TextBox txt, string defaultValue, bool needSetDefaultValue)
        {
            if (needSetDefaultValue == true) txt.Text = defaultValue;

            if (txt.Text != defaultValue) txt.ForeColor = Color.Black;

            txt.Attributes.Add("OnFocus", "if(this.value=='" + defaultValue + "') {this.value='';}this.style.color='black';");
            txt.Attributes.Add("OnBlur", "if(this.value==''){this.value='" + defaultValue + "';this.style.color='silver'} else if(this.value=='" + defaultValue + "'){this.style.color='silver'}");
        }

        /// <summary>
        /// 获取树控件中当前选中节点所在的索引
        /// </summary>
        /// <param name="tree"></param>
        /// <param name="selectedNode"></param>
        /// <returns></returns>
        public static int GetIndexForSelectedNode(TreeView tree, TreeNode selectedNode)
        {
            if (selectedNode != null)
            {
                TreeNodeCollection nodes = selectedNode.Parent == null ? tree.Nodes : selectedNode.Parent.ChildNodes;
                for (int i = 0; i < nodes.Count; i++)
                {
                    if (nodes[i] == selectedNode)
                    {
                        return i;
                    }
                }
            }
            return -1;
        }
        /// <summary>
        /// 获取包含Where关键字的SQL条件
        /// </summary>
        /// <param name="cond"></param>
        /// <returns></returns>
        public static string GetWhereCondition(string cond)
        {
            return cond.Trim() == "" ? "" : cond.StartsWith("where ") ? cond : "where " + cond;
        }
        /// <summary>
        /// 根据value值获取指定的节点
        /// </summary>
        /// <param name="nodes"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public static TreeNode GetNodeByValue(TreeNodeCollection nodes, string val)
        {
            for (int i = 0; i < nodes.Count; i++)
            {
                if (nodes[i].Value == val)
                {
                    return nodes[i];
                }
                else
                {
                    return GetNodeByValue(nodes[i].ChildNodes, val);
                }
            }
            return null;
        }
        /// <summary>
        /// 保存用于树节点中显示数字的条件
        /// </summary>
        /// <param name="pageInfo"></param>
        /// <param name="cond"></param>
        public static void SaveTreeNumberCondition(PageInfo pageInfo, string cond)
        {
            pageInfo.SetInfo("ALLCONDITION", GetWhereCondition(cond));
        }
        /// <summary>
        /// 获取用于树节点中显示数字的条件
        /// </summary>
        /// <param name="pageInfo"></param>
        /// <returns></returns>
        public static string GetTreeNumberCondition(PageInfo pageInfo)
        {
            var tmp = pageInfo.GetInfo("ALLCONDITION");
            return tmp == null ? "" : tmp.ToString();
        }
        /// <summary>
        /// 获取树控件中选中记录的id信息
        /// </summary>
        /// <param name="treeNode"></param>
        /// <returns></returns>
        public static int GetTreeNodeIDFromValue(TreeNode treeNode)
        {
            string tmp = treeNode.Value;
            if (string.IsNullOrEmpty(tmp))
            {
                return 0;
            }
            int index = tmp.IndexOf(";");
            if (index > -1)
            {
                tmp = tmp.Remove(index);
            }
            return CommonOP.GetInt(tmp, false);
        }
        /// <summary>
        /// 更新树节点的value信息，使之包含Text
        /// </summary>
        /// <param name="tree"></param>
        public static void UpdateTreeNodeValueWithText(TreeNode treeNode)
        {
            treeNode.Value += ";" + treeNode.Text;
            for (int i = 0; i < treeNode.ChildNodes.Count; i++)
            {
                UpdateTreeNodeValueWithText(treeNode.ChildNodes[i]);
            }
        }
        /// <summary>
        /// 获取逗号分隔的模块名称
        /// </summary>
        /// <returns></returns>
        public static string GetModuleNames(List<string> moduleList)
        {
            string res = "";
            for (int i = 0; i < moduleList.Count; i++)
            {
                res += ModuleName.ModuleDic[moduleList[i]] + " ; ";
            }
            return res.TrimEnd("; ".ToCharArray());
        }
        /// <summary>
        /// 获取最近的任务计划提醒字符串。
        /// 对于普通用户，只能查看自己的任务计划。
        /// 对于管理员，可查看当前企业的所有任务计划。
        /// </summary>
        /// <param name="enterpriseID"></param>
        /// <param name="commonUser"></param>
        /// <returns></returns>
        public static string GetNewestTaskPlanString(EnterpriseUser loginUser)
        {
            string newest = string.Empty;
            if (loginUser != null)
            {
                DataTable newsestList = null;
                if (loginUser.UserType == EnterpriseUserType.普通用户)
                {
                    newsestList = new Plan().GetRecordsByEnterpriseAndUser(loginUser.EnterpriseID, loginUser.ID, string.Empty);
                }
                else
                {
                    newsestList = new Plan().GetRecordsByEnterprise(loginUser.EnterpriseID, string.Empty);
                }

                foreach (DataRow row in newsestList.Rows)
                {
                    var ett = new Plan();
                    ett.GetProperties(row);
                    if (ett.ChangeDT.AddDays(CommonOP.GetInt(SystemConfig.AddNewAlertDays, true)) >= DateTime.Now && ett.Status != (int)TaskStatus.已完成)
                    {
                        newest += string.Format("[<a target='_blank' href='{0}\\UI\\EnterpriseAdmin\\Operation\\AddTaskPlan.aspx?pid={1}'>{2}</a>], ", BYFW.WebBase.BasePage.SiteRoot, ett.ID, ett.Name);
                    }
                }

                if (newest.Length > 1)
                {
                    newest = newest.Remove(newest.Length - 2, 2);
                }

            }
            return newest;
        }

        /// <summary>
        /// 获取本网站的临时目录
        /// </summary>
        /// <returns></returns>
        public static string GetTempFolder()
        {
            return Path.Combine(LDSP.Util.CommonService.SITEROOT, "TmpImg");
        }

        /// <summary>
        /// 获取快照，并添加详细链接。
        /// </summary>
        /// <returns></returns>
        public static string AppendLink(string snapshot, string logTextName, string keywords, int id, string relativeUrl = "")
        {
            string summary = snapshot;
            if (!string.IsNullOrEmpty(summary))
            {
                string url = relativeUrl + "LogTextPopup.aspx?type=" + logTextName + "&ID=" + id + "&keywords=" + HttpUtility.HtmlEncode(keywords);
                summary += "<a href=\"#\" onclick='windowOpen(\"" + url + "\")';>详细</a>";
            }

            return summary;
        }

        /// <summary>
        /// 将gridview转换成html格式的字符串
        /// </summary>
        /// <param name="gv"></param>
        /// <returns></returns>
        public static string ConvertGridViewToHtml(GridView gv)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            gv.RenderControl(hw);
            return sb.ToString();
        }

    }
}